﻿using System.Collections.ObjectModel;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace S2.Ui.ViewModels
{
    public class MainPageViewModel : BaseViewModel
    {
        public ICommand RegisterCommand { get; set; }
        public ICommand CancelCommand { get; set; }
        public ICommand LoadCommand { get; set; }

        private readonly HttpClient _httpClient;
        public MainPageViewModel()
        {
            RegisterCommand = new RelayCommand(async () => await RegisterAsync());
            LoadCommand = new RelayCommand(async () => await PageLoaded());
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
            };
            _httpClient = new HttpClient(handler)
            {
                BaseAddress = new System.Uri("https://192.168.1.17")
            };
        }
        private async Task PageLoaded()
        {
            await LoadSecurityQuestions();
        }

        private async Task LoadSecurityQuestions()
        {
            var url = "/api/security-question";
            var response = await _httpClient.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                // 必须引用System.Text.Json 库
                var questions = JsonSerializer.Deserialize<ObservableCollection<string>>(json);
                SecurityQuestionSources = questions;
            }

        }
        public static bool IsEmail(string inputData)
        {
            Regex RegEmail = new Regex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$");
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }
        private async Task RegisterAsync()
        {
            if (string.IsNullOrWhiteSpace(FirstName) ||
                string.IsNullOrWhiteSpace(LastName) ||
                string.IsNullOrWhiteSpace(EmailAddress) ||
                string.IsNullOrWhiteSpace(Password) ||
                string.IsNullOrWhiteSpace(ConfirmPassword) ||
                string.IsNullOrWhiteSpace(SecurityQuestion) ||
                string.IsNullOrWhiteSpace(SecurityAnswer))
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Please fill in all fields.", "OK");
                return;
            }
            if (!IsEmail(EmailAddress))
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Please enter a valid email address.", "OK");
                return;
            }
            if (Password != ConfirmPassword)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Passwords do not match.", "OK");
                return;
            }
            var url = "/api/register";
            var user = new User
            {
                Emial = EmailAddress,
                FirstName = FirstName,
                LastName = LastName,
                Password = Password,
                安全答案 = SecurityAnswer,
                安全问题 = SecurityQuestion,
            };
            var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(user), System.Text.Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync(url, content);
            var responseContent = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                await Application.Current.MainPage.DisplayAlert("Success", "Register success!", "OK");
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Register failure", "OK");
            }

        }

        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; OnPropertyChanged(); }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; OnPropertyChanged(); }
        }

        private string _emailAddress;

        public string EmailAddress
        {
            get { return _emailAddress; }
            set { _emailAddress = value; OnPropertyChanged(); }
        }
        private string _password;

        public string Password
        {
            get { return _password; }
            set { _password = value; OnPropertyChanged(); }
        }

        private string _confirmPassword;

        public string ConfirmPassword
        {
            get { return _confirmPassword; }
            set { _confirmPassword = value; OnPropertyChanged(); }
        }

        private string _securityQuestion;

        public string SecurityQuestion
        {
            get { return _securityQuestion; }
            set { _securityQuestion = value; OnPropertyChanged(); }
        }

        private string _securityAnswer;

        public string SecurityAnswer
        {
            get { return _securityAnswer; }
            set { _securityAnswer = value; OnPropertyChanged(); }
        }

        private bool _subscribeMailing;

        public bool SubscribeMailing
        {
            get { return _subscribeMailing; }
            set { _subscribeMailing = value; OnPropertyChanged(); }
        }


        private ObservableCollection<string> _securityQuestionSources;

        public ObservableCollection<string> SecurityQuestionSources
        {
            get { return _securityQuestionSources; }
            set { _securityQuestionSources = value; OnPropertyChanged(); }
        }


    }
}
